package br.com.vagacerta.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.vagacerta.modelo.Email;


@Repository
public class EmailDAO {

	private Connection connection;

	@Autowired
	public EmailDAO(DataSource dataSource) {
		try {
			this.connection = dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	protected void insereEmailCliente(Email[] emails, long codigoCliente) {
		try {

			for (Email email : emails) {
				if (email != null) {
					String sql = "INSERT INTO EMAIL (COD_CLIENTE, ENDERECO_EMAIL) VALUES (?, ?)";

					PreparedStatement stmt;
					stmt = connection.prepareStatement(sql);

					stmt.setLong(1, codigoCliente);
					stmt.setString(2, email.getEmail());

					stmt.execute();
					stmt.close();

				}

			}

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	public void excluiEmailPorIdCliente(long idCliente) throws SQLException {
		try {
			String sql = "DELETE FROM EMAIL WHERE COD_CLIENTE = ?";

			PreparedStatement stmt;
			stmt = connection.prepareStatement(sql);

			stmt.setLong(1, idCliente);

			stmt.execute();
			stmt.close();

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	public List<Email> consultaEmailsPorIdCliente(long idCliente) {
		try {
			String sql = "SELECT * FROM EMAIL WHERE COD_CLIENTE  = ?";

			PreparedStatement stmt;
			stmt = connection.prepareStatement(sql);

			stmt.setLong(1, idCliente);

			ResultSet rs = stmt.executeQuery();
			List<Email> listaEmail = new ArrayList<Email>();


			while (rs.next()) {
				Email email = new Email();
				email.setCodigoEmail(rs.getLong("COD_EMAIL"));
				email.setCodigoCliente(rs.getLong("COD_CLIENTE"));
				email.setEmail(rs.getString("ENDERECO_EMAIL"));
				listaEmail.add(email);

			}
			
			rs.close();
			stmt.close();

			return listaEmail;

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}
	
}
